<template>
	<view>
		<view class="head-bg padding-lr">
			<!-- <view @click="getProfile" class="user-info flex align-center justify-between">
				<view class="flex align-center">
					<image class="round head-img" :src="wxAvatar ? wxAvatar : '../../static/head.png'"
						mode="aspectFill">
					</image>
					<view class="mobile"> {{ nickName ? nickName : '请登录' }} </view>
				</view>
			</view> -->
			<view class="user-info flex align-center justify-between">
				<view class="flex align-center">
					<image class="round head-img" :src="wxAvatar ? wxAvatar : '../../static/head.png'"
						mode="aspectFill">
					</image>
					<view v-if="phonenumber === ''" style="margin-left: 20rpx;">
						<button style="width: 200rpx;height: 80rpx;font-size: 32rpx;border-radius: 30rpx;" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">点击登陆</button>
					</view>
					<view v-else style="margin-left: 20rpx;font-weight: 700;">
						{{ phonenumber }}
					</view>
				</view>
			</view>
		</view>
		<view class="mine-list padding-lr">
			<view v-if="false" @click="navTo('help')" class="flex item align-center">
				<u-icon name="/static/icon/mine-xin.png" size="40"></u-icon>
				<view class="flex align-center justify-between solid-bottom margin-left-sm">
					<view class="title">使用指南</view>
					<view class="flex align-center">
						<view class="desc">提问的艺术</view>
						<u-icon name="arrow-right" color="#848B9E" size="24"></u-icon>
					</view>
				</view>
			</view>
			<view v-if="false" @click="toVip" class="flex item align-center">
				<u-icon name="/static/icon/mine-gift.png" size="40"></u-icon>
				<view class="flex align-center justify-between solid-bottom margin-left-sm">
					<view class="title">开通权益</view>
					<view class="flex align-center">
						<view class="desc">享专属特权</view>
						<u-icon name="arrow-right" color="#848B9E" size="24"></u-icon>
					</view>
				</view>
			</view>

			<button v-if="false" open-type="feedback" class="flex item align-center">
				<u-icon name="/static/icon/mine-xin.png" size="40"></u-icon>
				<view class="flex align-center justify-between solid-bottom margin-left-sm">
					<view class="title">问题反馈</view>
					<view class="flex align-center">
						<u-icon name="arrow-right" color="#848B9E" size="24"></u-icon>
					</view>
				</view>
			</button>

			<view @click="logout" class="flex item align-center">
				<u-icon name="/static/icon/quit.png" size="30"></u-icon>
				<view class="flex align-center justify-between solid-bottom margin-left-sm">
					<view class="title">退出登录</view>
					<view class="flex align-center">
						<u-icon name="arrow-right" color="#848B9E" size="24"></u-icon>
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="兑换码" :value="rede_code" placeholder="请输入兑换码"
				@confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
		<daxiang-getUserProfile ref="getUserProfile"></daxiang-getUserProfile>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				showContact: false,
				showDevNav: false,
				rede_code: '',
				loginCode: "",
				phonenumber: "",
				userId: "",
				wxAvatar: "",
				openId: "",
				showPay: false,
				code: ''
			};
		},
		computed: {

		},
		onLoad() {
			const userInfo = uni.getStorageSync('userInfo');
			console.log('进来userInfo', userInfo)

			this.phonenumber = userInfo.phonenumber
			this.userId = userInfo.userId
			this.openId = userInfo.openid
			this.wxAvatar = userInfo.wxAvatar
			console.log('phonenumber', this.phonenumber)
			

		},
		onShareAppMessage() {
			return {
				title: '快来和胖胖聊天呀',
				path: '/pages/index/home?share_m_id=' + this.userInfo.nickName,
				imageUrl: 'https://s1.ax1x.com/2023/03/19/ppYVZRK.jpg'
			}
		},
		onShow() {
			 wx.login({
				    success: function(res) {
					    // this.code = JSON.stringify(res.code)
						// this.code = res.code
						// console.log('点击拿code1', this.code)
				    }
			  })

		},
		methods: {
			toVip() {
				uni.navigateTo({
					url: "/pages/vip/vip"
				})
			},
			navTo(id) {
				switch (id) {
					case "help":
						uni.navigateTo({
							url: '/pages/content/help'
						})
						break;
				}
			},
			showContactPop() {
				this.showContact ? this.showContact = false : this.showContact = true;
			},
			call() {
				uni.makePhoneCall({
					phoneNumber: '010-86203046'
				})
			},
			// getProfile(e) {
			// 	const userInfo = uni.getStorageSync('userInfo');
			// 	console.log('userInfo*******', userInfo)
			// 	if (userInfo.userId) {
			// 		return
			// 	}
			// 	let that = this
			// 	wx.login({
			// 	    success: function(res) {
			// 			console.log('res', res)

			// 			that.code = res.code
			// 			that.$refs.getUserProfile.open({
			// 		        desc: '授权登录',
			// 		        success: e => {
			// 			        console.log('e', e)
			// 			        // 先获取用户token
			// 			        that.$request('/auth/wxMiniLogin', 'POST', {
			// 				        userId: that.userId,
			// 				        nickName: e.userInfo.nickName,
			// 				        wxAvatar: e.userInfo.avatarUrl,
			// 				        openId: that.openId,
			// 				        code: that.code,
			// 						tenantId: '00001'
			// 			        }, {
			// 				        'content-type': 'application/json'
			// 			        }).then(res => {
			// 				        if (res.code == 200) {
			// 							const token = res.data.token
			// 							if (token) {
			// 								uni.setStorageSync('token', token)
			// 								that.$request('/wx/user/getInfo', 'GET', {
			// 								}).then(item => {
			// 									console.log('用户信息', item)
            //                                     uni.setStorageSync('userInfo', item.data)
			// 									console.log('存下来', uni.getStorageSync('userInfo'));
			// 									const userInfo = uni.getStorageSync('userInfo');
			// 									this.nickName = userInfo.nickName
			//                                     this.userId = userInfo.userId
			//                                     this.openId = userInfo.openid
			//                                     this.wxAvatar = userInfo.wxAvatar
			// 									uni.reLaunch({
			// 						                url: "/pages/index/index"
			// 					                })
			// 									console.log('重新跳转了', that.nickName)
			// 								})
			// 							}
			// 				        }
			// 			        })
			// 		        },
			// 		    fail: err => {
			// 			    console.log(err)
			// 	     	}
			// 	    });
			// 	    }
			//   })

			// },
			getPhoneNumber(e) {
				console.log('e', e.detail)
                if (e.detail.errMsg !== 'getPhoneNumber:ok') {
                    // 用户拒绝授权
                    uni.showToast({
                        title: '您拒绝了获取手机号授权',
                        icon: 'none'
                    });
                    return;
                }

        const { encryptedData, iv } = e.detail;

        // 先调用 wx.login 获取 code
        wx.login({
          success: (res) => {
            if (res.code) {
              this.loginCode = res.code;
              if (!encryptedData || !iv || !this.loginCode) {
                uni.showToast({
                  title: '获取手机号信息失败',
                  icon: 'none'
                });
                return;
              }

              this.$request('/auth/wxMiniPhoneLogin', 'POST', {
                code: this.loginCode, // 使用 wx.login 获取的 code
                encryptedData,
                iv,
                tenantId: '00001'
              }, {
                'content-type': 'application/json'
              })
                  .then((res) => {
                    if (res.code === 200) {
                      console.log('登录成功');
                      uni.showToast({
                        title: '登录成功',
                        icon: 'success'
                      });
                      // 可以在这里添加登录成功后的逻辑，如跳转到首页等
					  const token = res.data.token
							if (token) {
								uni.setStorageSync('token', token)
									this.$request('/wx/user/getInfo', 'GET', {
											}).then(item => {
												console.log('用户信息', item)
                                                uni.setStorageSync('userInfo', item.data)
												console.log('存下来', uni.getStorageSync('userInfo'));
												const userInfo = uni.getStorageSync('userInfo');
												this.phonenumber = userInfo.phonenumber
			                                    this.userId = userInfo.userId
			                                    this.openId = userInfo.openid
			                                    this.wxAvatar = userInfo.wxAvatar
												uni.reLaunch({
									                url: "/pages/index/index"
								                })
												console.log('重新跳转了', this.phonenumber)
											})
										}
                    } else {
                      console.error('登录失败', res);
                      uni.showToast({
                        title: '登录失败，请重试',
                        icon: 'none'
                      });
                    }
                  })
                  .catch((err) => {
                    console.error('请求出错', err);
                    uni.showToast({
                      title: '网络请求出错',
                      icon: 'none'
                    });
                  });
            } else {
              uni.showToast({
                title: '获取登录凭证失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            console.error('wx.login 调用失败', err);
            uni.showToast({
              title: '获取登录凭证失败',
              icon: 'none'
            });
          }
        });
			},



			rede() {
				this.$refs.popup.open()
			},
			dialogInputConfirm(val) {
				if (!val) {
					uni.showModal({
						content: "请输入兑换码！"
					});
					return
				}
				uni.showLoading({
					title: '兑换中...'
				})
				this.$request('/api/Redemption/rede', 'POST', {
					code: val
				}).then(res => {
					console.log(res)
					if (res.status == 200) {
						this.$refs.inputClose.close()
						uni.hideLoading()
						uni.showModal({
							content: "已兑换成功"
						})
						this.rede_code = ""
						this.$store.commit('syncUserNum', res.data.num)
					} else {
						this.$refs.inputClose.close()
						uni.hideLoading()
						uni.showModal({
							content: res.status == 201 ? res.msg : '核销失败'
						})
					}
				})
			},
			logout() {
				uni.removeStorageSync('userInfo')
				uni.removeStorageSync('token')
				this.$request("/auth/logout", "Post").then((res) => {
					if (res.code == 200) {
						uni.reLaunch({
                            url: "/pages/mine/mine"
						})
					} else {
						this.$failToast('服务器繁忙，请稍后再试');
					}
				});

			}
		},
	};
</script>

<style>
	/*每个页面公共css */
	@import url("@/static/style/color-ui.css");
</style>

<style lang="scss">
	.head-bg {
		/* #ifndef H5 */
		padding-top: var(--status-bar-height);
		margin-top: 60rpx;
		/* #endif */
		background-image: url('');
		background-repeat: no-repeat;
		background-size: 100%;
		// width: 100%;
		height: 574rpx;

		.user-info {
			/* #ifdef H5 */
			padding-top: 60rpx;
			/* #endif */
			/* #ifndef H5 */
			padding-top: 30rpx;

			/* #endif */
			.head-img {
				width: 120rpx;
				height: 120rpx;
			}

			.mobile {
				padding-left: 23rpx;
				font-size: 36rpx;
				font-weight: bold;
				color: #222222;
			}

			.info-edit {
				font-size: 24rpx;
				font-weight: 500;
				color: #848b9e;
				line-height: 18rpx;
				padding-right: 12rpx;
			}
		}

		// .vip-bg {
		// 	background-image: url("@/static/img/mine/mine-vip-bg.png");
		// 	background-repeat: no-repeat;
		// 	background-size: 100%;
		// 	// width: calc(100% - 60rpx);
		// 	height: 133rpx;
		// 	padding: 30rpx 24rpx 30rpx 30rpx;
		// 	margin-top: 50rpx;

		// 	.taocan {
		// 		color: #ffffff;

		// 		.title {
		// 			font-size: 30rpx;
		// 			font-weight: bold;
		// 			line-height: 33rpx;
		// 		}

		// 		.desc {
		// 			font-size: 24rpx;
		// 			font-weight: 500;
		// 			line-height: 33rpx;
		// 			padding-top: 19rpx;
		// 		}
		// 	}

		// 	.cu-btn {
		// 		height: 48rpx;
		// 		background: linear-gradient(90deg, #ffefc9 0%, #e9c98d 100%);
		// 		border-radius: 24rpx;
		// 		font-size: 24rpx;
		// 		font-weight: bold;
		// 		color: #863f18;
		// 		line-height: 35rpx;
		// 	}
		// }
	}

	.mine-list {
		margin-top: -281rpx;

		button {
			border: none;
			margin: 0;
			padding: 0;
			background-color: inherit;
		}

		button::after {
			border: none;
		}

		.item {
			// width: calc(100% - 60rpx);

			.solid-bottom {
				width: 100%;
			}

			.title {
				padding-top: 50rpx;
				padding-bottom: 50rpx;
				font-size: 32rpx;
				font-weight: bold;
				color: #141e34;
				line-height: 56rpx;
			}

			.desc {
				padding-right: 13rpx;
				font-size: 28rpx;
				font-weight: 500;
				color: #848b9e;
				line-height: 40rpx;
			}
		}
	}
</style>
